var clusterini = null;
var iniDic = null;

layui.define(['jquery', 'form', 'table', 'formRender'], function (exports) {
    var form = layui.form,
        layer = layui.layer,
        formRender = layui.formRender,
        table = layui.table,
        $ = layui.$;
    var loadIndex = layer.load();
    $.ajax({
        url: '/api/get_dic',
        type: 'GET',
        dataType: 'JSON',
        success: function (data) {
            layer.close(loadIndex);
            if (data.code) {
                layer.open({
                    title: '提示',
                    msg: data.msg
                });
            }
            clusterini = data.data.clusterIni;
            iniDic = data.data;
        },
        error: function (xhr) {
            layer.close(loadIndex);
            layer.open({
                title: '提示',
                content: '糟糕，出问题了。'
            });
        }
    });


    var clusterEditor = {
        showAdd: function () {
            this._showClusterEdit(clusterini, {
                winTitle: '添加存档',
                commit: 'add_cluster'
            });
        },

        showEdit: function (clusterId) {
            var _self = this;
            var loadIndex = layer.load();
            $.ajax({
                url: '/api/get_clusterini',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    cluster_id: clusterId
                },
                success: function (data) {
                    layer.close(loadIndex);
                    if (data.code) {
                        layer.open({
                            title: '提示',
                            content: data.data
                        });
                        return;
                    }
                    _self._showClusterEdit(data.data, {
                        winTitle: '修改存档',
                        readonly: ['cluster_dir_name'],
                        commit: 'save_clusterini'
                    });
                },
                error: function (xhr) {
                    layer.close(loadIndex);
                    layer.open({
                        title: '提示',
                        content: '糟糕，出问题了。'
                    });
                }
            })
        },

        _showClusterEdit: function (clusterIni, inOption) {
            var option = $.extend({
                winTitle: '存档',
                commit: 'add_cluster',
                readonly: []
            }, inOption || {});

            var index = layer.open({
                title: option.winTitle,
                type: 1,
                area: ['800px', '600px'],
                content: `
                <div class="layuimini-main">
                    <div id="cluster_add" class="layui-form layuimini-form" lay-filter="cluster_add_f">
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="cluster_add_f" style="margin-left: 150px;">提交</button>
                            </div>
                        </div>
                    </div>
                </div>`,
            });

            var formData = $.extend({
                BASE: {
                    cluster_dir_name: {
                        zh: '存档名称',
                        type: 'text'
                    },
                    cluster_token: {
                        zh: '饥荒服务端令牌',
                        type: 'text'
                    }
                }
            }, clusterIni);
            for (var name of option.readonly) {
                var flag = true;
                for (var category in formData) {
                    for (var key in formData[category]) {
                        if (key == name) {
                            formData[category][name].readonly = true;
                            flag = false;
                            break;
                        }
                    }
                    if (!flag) break;
                }
            }

            formRender.init('#cluster_add', formData, true);
    
            // 当前弹出层，防止ID被覆盖
            var parentIndex = layer.index;
    
            //监听提交
            form.on('submit(cluster_add_f)', function (data) {
    
                var loadIndex = layer.load();
                $.ajax({
                    type: 'POST',
                    dataType: 'JSON',
                    url: '/api/' + option.commit,
                    data: data.field,
                    success: function (data) {
                        layer.close(loadIndex);
                        if (data.code) {
                            layer.open({
                                title: '提示',
                                content: data.msg,
                            })
                        } else {
                            layer.msg('操作成功。');
                            window.clusterTable.reload();
                            layer.close(parentIndex);
                        }
                    },
                    error: function (xhr) {
                        layer.close(loadIndex);
                        layer.open({
                            title: '提示',
                            content: '糟糕，出问题了。'
                        });
                    }
                });
    
                return false;
            });
        },


        blacklist: function(clusterId) {
            this.__nameList({
                type: 'blacklist',
                cluster_id: clusterId
            });
        },

        whitelist: function(clusterId) {
            this.__nameList({
                type: 'whitelist',
                cluster_id: clusterId
            });
        },

        adminlist: function(clusterId) {
            this.__nameList({
                type: 'adminlist',
                cluster_id: clusterId
            });
        },

        __nameList: function (inOption) {
            var option = $.extend({
                type: 'blacklist',
                cluster_id: '---'
            }, inOption || {})
            var loadIndex = layer.load();
            $.ajax({
                url: '/api/get_namelist' ,
                type: 'POST',
                dataType: 'JSON',
                data: {
                    type: option.type,
                    cluster_id: option.cluster_id
                },
                success: function (data) {
                    layer.close(loadIndex);
                    if (data.code) {
                        layer.open({
                            title: '提示',
                            content: data.msg
                        })
                        return;
                    }

                    layer.prompt({
                        formType: 2,
                        value: data.data,
                        title: {
                            blacklist: '黑名单列表',
                            whitelist: '白名单列表',
                            adminlist: '管理员列表'
                        }[option.type] || '请输入内容',
                        area: ['400px', '100px'], //自定义文本域宽高
                        yes: function (index, layero) {
                            var value = layero.find(".layui-layer-input").val();
                            loadIndex = layer.load();
                            $.ajax({
                                url: '/api/save_namelist',
                                type: 'POST',
                                dataType: 'JSON',
                                data: {
                                    type: option.type,
                                    cluster_id: option.cluster_id,
                                    content: value
                                },
                                success: function (data) {
                                    layer.close(loadIndex);
                                    if (data.code) {
                                        layer.open({
                                            title: '提示',
                                            content: data.msg
                                        });
                                        return;
                                    }
                                    layer.close(index);
                                    layer.msg(data.msg);
                                },
                                error: function (xhr) {
                                    layer.close(loadIndex);
                                    layer.open({
                                        title: '提示',
                                        content: '糟糕，出问题了。'
                                    });
                                }
                            })
                        }
                    });
                },
                error: function (xhr) {
                    layer.close(loadIndex);
                    layer.open({
                        title: '提示',
                        content: '糟糕，出问题了。'
                    });
                }
            });
        },


        masterEdit: function(clusterId) {
            this.__mcaEdit({
                type: 'Master',
                cluster_id: clusterId
            });
        },

        cavesEdit: function(clusterId) {
            this.__mcaEdit({
                type: 'Caves',
                cluster_id: clusterId
            });
        },

        __mcaEdit: function(inOption) {
            var option = $.extend({
                type: 'Master',
                cluster_id: ''
            }, inOption || {});
            var loadIndex = layer.load();
            $.ajax({
                url: '/api/get_leveldataoverride',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    type: option.type,
                    cluster_id: option.cluster_id
                },
                success: function(data) {
                    layer.close(loadIndex);
                    if (data.code) {
                        layer.open({
                            title: '提示',
                            content: data.msg
                        });
                        return;
                    }

                    var index = layer.open({
                        title: {
                            Master: '地表配置',
                            Caves: '洞穴配置'
                        }[inOption.type] || '修改',
                        type: 1,
                        area: ['800px', '600px'],
                        content: `
                        <div class="layuimini-main">
                            <div id="mca_edit" class="layui-form layuimini-form" lay-filter="mca_edit_f">
                                <div class="layui-form-item">
                                    <div class="layui-input-block">
                                        <button class="layui-btn" lay-submit lay-filter="mca_edit_f" style="margin-left: 150px;">提交</button>
                                    </div>
                                </div>
                            </div>
                        </div>`,
                    });
                    formRender.init('#mca_edit', data.data, true);
    
                    //监听提交
                    form.on('submit(mca_edit_f)', function (data) {
                        var loadIndex = layer.load();
                        $.ajax({
                            url: '/api/save_leveldataoverride',
                            type: 'POST',
                            dataType: 'JSON',
                            data: data.field,
                            success: function (data) {
                                layer.close(loadIndex);
                                if (data.code) {
                                    layer.open({
                                        title: '提示',
                                        content: data.msg
                                    });
                                    return;
                                }
                                layer.close(index);
                                layer.msg(data.msg);
                            },
                            error: function (xhr) {
                                layer.close(loadIndex);
                                layer.open({
                                    title: '提示',
                                    content: '糟糕，出问题了。'
                                });
                            }
                        });
                    });
                },
                error: function (xhr) {
                    layer.close(loadIndex);
                    layer.open({
                        title: '提示',
                        content: '糟糕，出问题了。'
                    });
                }
            })
        },

        modsEdit: function(clusterId) {
            var loadIndex = layer.load();
            $.ajax({
                url: '/api/get_cluster_mods',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    cluster_id: clusterId
                },
                success: function (data) {
                    layer.close(loadIndex);
                    if (data.code) {
                        layer.open({
                            title: '提示',
                            content: data.msg
                        });
                        return;
                    }

                    $.each(data.data, function (id, ele) {
                        ele.LAY_CHECKED = ele.__enabled;
                    });

                    var clusterModsIndex = layer.open({
                        type: 1,
                        title: '存档MOD管理 - ' + clusterId,
                        content: `
                        <script type="text/html" id="clusterModsTableToolBar">
                            <button class="layui-btn layui-btn-sm" lay-event="saveMods">保存</button>
                        </script>
                        <table id="clusterModsTable" style="width: 100%" lay-filter="clusterModsTable"></table>
                        `,
                    });
                    layer.full(clusterModsIndex);
                    setTimeout(() => {
                        var clusterModsTable = table.render({
                            elem: '#clusterModsTable',
                            data: data.data,
                            page: false,
                            limit: 999999999999,
                            toolbar: '#clusterModsTableToolBar',
                            defaultToolbar: ['filter'],
                            cols: [[
                                { type: 'checkbox' },
                                { field: '__modId', title: 'MODID', width: 120 },
                                { field: 'name', title: '名称', width: 300  },
                                { field: 'version', title: '版本', width: 100 },
                                { field: 'author', title: '作者', width: 150 },
                                { field: 'description', title: '描述' }
                            ]]
                        });

                        table.on('toolbar(clusterModsTable)', function (obj) {
                            if ('saveMods' == obj.event) {
                                // var toEnableMods = obj.config.data.filter(function (a) { return a.LAY_CHECKED });
                                var toEnableMods = [];
                                $.each(obj.config.data, function (id, ele) {
                                    if (ele.LAY_CHECKED) {
                                        toEnableMods.push({
                                            __modId: ele.__modId
                                        });
                                    }
                                });
                                var loadIndex = layer.load();
                                $.ajax({
                                    url: '/api/save_cluster_mods',
                                    type: 'POST',
                                    dataType: 'JSON',
                                    data: {
                                        cluster_id: clusterId,
                                        data: JSON.stringify(toEnableMods)
                                    },
                                    success: function (data) {
                                        layer.close(loadIndex);
                                        if (data.code) {
                                            layer.open({
                                                title: '提示',
                                                content: data.msg
                                            });
                                            return;
                                        }
                                        layer.close(clusterModsIndex);
                                        layer.msg(data.msg);
                                    },
                                    error: function (xhr) {
                                        layer.close(loadIndex);
                                        layer.open({
                                            title: '提示',
                                            content: '糟糕，出问题了。'
                                        });
                                    }
                                });
                            }
                        });
                    }, 200);
                },
                error: function (xhr) {
                    layer.close(loadIndex);
                    layer.open({
                        title: '提示',
                        content: '糟糕，出问题了。'
                    });
                }
            });
        }
    };

    exports('clusterEditor', clusterEditor);
});
